from django.shortcuts import render
from circle.models import *
from userauth.views import *
from django.shortcuts import HttpResponse, render, redirect
from django.contrib.auth.decorators import login_required

def getrealname(user):
    return UserInformation.objects.get(uid = user).realname

# Create your views here.
class Circle:
    def Mainpage(request):
        if request.user.id == None:
            return redirect("/user/login")
        result = []
        cont = Content.objects.all()
        for item in cont:
            comm_list = []
            comm = Comment.objects.filter(tid = item.id)
            for i in comm:
                comm_list.append([getrealname(i.uid),i.content])
            like_list = []
            like_str = ""
            like = Like.objects.filter(tid = item.id)
            for i in like:
                like_list.append(getrealname(i.uid))
            if len(like_list) >= 4 :
                like_str = like_list[-4]+" "+like_list[-3]+" "+like_list[-2]+" "+like_list[-1]+"等已点赞"
            elif len(like_list) > 0:
                like_str = " ".join(str(i) for i in like_list) + "已点赞"
            result.append([item.id,getrealname(item.uid),item.content,item.time.strftime('%H:%M'),comm_list,like_str,len(like_list)])
        #print(result)
        return render(request, 'circle_main.html',{"result":result})
    def Like(request):
        if request.user.id == None:
            return redirect("/user/login")
        if request.method != "POST":
            return redirect("/circle")
        tid = request.POST["tid"]
        if Like.objects.filter(tid = tid,uid = request.user.id).count() == 0:
            z = Like(uid=request.user.id,tid=tid)
            z.save()
            return HttpResponse("点赞成功")
        else:
            return HttpResponse("您已点赞")
